//
//  UIButton+Event.m
//  KKRequestDemo
//
//  Created by Mac mini on 16/1/27.
//  Copyright © 2016年 JuniorCodingPerson. All rights reserved.
//

#import "UIButton+Event.h"

#import <objc/runtime.h>

@implementation UIButton (Event)

static const void *UIButtonEventHandleValue = &UIButtonEventHandleValue;

@dynamic eventHandle;

- (UIButtonEventHandle)eventHandle {
    return objc_getAssociatedObject(self, UIButtonEventHandleValue);
}

- (void)setEventHandle:(UIButtonEventHandle)eventHandle {
    
    if (eventHandle && self.eventHandle == nil) {
        [self addTarget: self action: @selector(kk_onClick:) forControlEvents: UIControlEventTouchUpInside];
    }
    else if(eventHandle == nil && self.eventHandle){
        [self removeTarget: self action: @selector(kk_onClick:) forControlEvents: UIControlEventTouchUpInside];
    }
    
    objc_setAssociatedObject(self, UIButtonEventHandleValue, eventHandle, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

#pragma mark - Private methods

- (void)kk_onClick:(UIButton *)button {
    
    if (self.eventHandle) {
        self.eventHandle();
    }
}

@end
